export function toast(title,icon='none',duration=2000){
	uni.showToast({
		title,
		icon,
		duration
	})
}

export function modal(content,title='提醒',func_success=() => {},func_cancel=() => {}){
	uni.showModal({
		title,
		content,
		success: (res) => {
			if(res.confirm){
				func_success()
			} else {
				func_cancel()
			}
		}
	})
}

export function loading(title){
	uni.showLoading({
		title
	})
}

export function routeUrl(url,type='redirectTo'){
	switch(type){
		case 'navigateTo':
			uni.navigateTo({
				url
			})
			break
		case 'redirectTo':
			uni.redirectTo({
				url
			})
			break
		case 'switchTab':
			uni.switchTab({
				url
			})
			break
	}
}

// 字符串转十六进制
export function strToHex(str){
	let hexStr = "";
	for (let i = 0; i < str.length; i++) {
	    let charCode = str.charCodeAt(i);
	    hexStr += charCode.toString(16).padStart(2, '0');
	}
	return hexStr
}

/**
 * Created by PanJiaChen on 16/11/18.
 */
import {
	hunterInfoDict,
	hunterAlarmDict
} from './constant'
/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
	if (arguments.length === 0 || !time) {
		return null
	}
	const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
	let date
	if (typeof time === 'object') {
		date = time
	} else {
		if ((typeof time === 'string')) {
			if ((/^[0-9]+$/.test(time))) {
				// support "1548221490638"
				time = parseInt(time)
			} else {
				// support safari
				// https://stackoverflow.com/questions/4310953/invalid-date-in-safari
				time = time.replace(new RegExp(/-/gm), '/')
			}
		}

		if ((typeof time === 'number') && (time.toString().length === 10)) {
			time = time * 1000
		}
		date = new Date(time)
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay()
	}
	const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
		const value = formatObj[key]
		// Note: getDay() returns 0 on Sunday
		if (key === 'a') {
			return ['日', '一', '二', '三', '四', '五', '六'][value]
		}
		return value.toString().padStart(2, '0')
	})
	return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
	if (('' + time).length === 10) {
		time = parseInt(time) * 1000
	} else {
		time = +time
	}
	const d = new Date(time)
	const now = Date.now()

	const diff = (now - d) / 1000

	if (diff < 30) {
		return '刚刚'
	} else if (diff < 3600) {
		// less 1 hour
		return Math.ceil(diff / 60) + '分钟前'
	} else if (diff < 3600 * 24) {
		return Math.ceil(diff / 3600) + '小时前'
	} else if (diff < 3600 * 24 * 2) {
		return '1天前'
	}
	if (option) {
		return parseTime(time, option)
	} else {
		return (
			d.getMonth() +
			1 +
			'月' +
			d.getDate() +
			'日' +
			d.getHours() +
			'时' +
			d.getMinutes() +
			'分'
		)
	}
}

/**
 * 美化时间
 * @param {Object} datetime
 */
export function getBeautifulDate(datetime) {
	if (datetime == undefined) {
		return false;
	} else {
		const minute = 1000 * 60;
		const hour = minute * 60;
		const day = hour * 24;
		const halfamonth = day * 15;
		const month = day * 30;

		datetime = datetime.replace(/\-/g, "/");
		const sTime = new Date(datetime).getTime(); //把时间pretime的值转为时间戳
		const now = new Date().getTime(); //获取当前时间的时间戳
		const diffValue = now - sTime;
		if (diffValue < 0) {
			console.log("结束日期不能小于开始日期！");
		}

		const monthC = diffValue / month;
		const weekC = diffValue / (7 * day);
		const dayC = diffValue / day;
		const hourC = diffValue / hour;
		const minC = diffValue / minute;

		if (monthC >= 1) {
			return (parseInt(monthC) + "月前");
		} else if (weekC >= 1) {
			return (parseInt(weekC) + "周前")
		} else if (dayC >= 1) {
			return (parseInt(dayC) + "天前")
		} else if (hourC >= 1) {
			return (parseInt(hourC) + "小时前")
		} else if (minC >= 1) {
			return (parseInt(minC) + "分钟前")
		} else {
			return ("刚刚")
		}
	}
}


/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
	const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
	if (!search) {
		return {}
	}
	const obj = {}
	const searchArr = search.split('&')
	searchArr.forEach(v => {
		const index = v.indexOf('=')
		if (index !== -1) {
			const name = v.substring(0, index)
			const val = v.substring(index + 1, v.length)
			obj[name] = val
		}
	})
	return obj
}

/**
 * 去除对象中值为null、undefined、''的字段
 * @param {*} obj
 * @returns
 */
export function removeEmptyField(obj) {
	var newObj = {}
	if (typeof obj === 'string') {
		obj = JSON.parse(obj)
	}
	if (obj instanceof Array) {
		newObj = []
	}
	if (obj instanceof Object) {
		for (var attr in obj) {
			// eslint-disable-next-line no-prototype-builtins
			if (obj.hasOwnProperty(attr) && obj[attr] !== '' && obj[attr] !== null && obj[attr] !== undefined) {
				if (obj[attr] instanceof Object) {
					newObj[attr] = removeEmptyField(obj[attr])
				} else if (typeof obj[attr] === 'string' && ((obj[attr].indexOf('{') > -1 && obj[attr].indexOf(
						'}') > -1) || (obj[attr].indexOf('[') > -1 && obj[attr].indexOf(']') > -1))) {
					try {
						var attrObj = JSON.parse(obj[attr])
						if (attrObj instanceof Object) {
							newObj[attr] = removeEmptyField(attrObj)
						}
					} catch (e) {
						newObj[attr] = obj[attr]
					}
				} else {
					newObj[attr] = obj[attr]
				}
			}
		}
	}
	return newObj
}

export function setArrayItem(key, value) {
	value = JSON.stringify(value)
	uni.setStorageSync(key, value)
}

export function getArrayItem(key) {
	if (uni.getStorageSync(key)) {
		try {
			return JSON.parse(uni.getStorageSync(key))
		} catch (err) {
			console.log(err)
			return []
		}
	}
	return []
}

export function convertArr2Obj(arr, key) {
	return arr.reduce((obj, v) => {
		obj[v[key]] = v
		return obj
	}, {})
}

/**
 * 生成随机字符串
 * @param {*} length
 * @returns
 */
export function generateRandStr(length = 10) {
	let text = ''
	const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
	for (var i = 0; i < length; i++) {
		text += possible.charAt(Math.floor(Math.random() * possible.length))
	}

	return text
}

/**
 * @param {Array} arr
 * @returns {Array}
 */
export function uniqueArr(arr) {
	return Array.from(new Set(arr))
}

export function clearCache() {
	const keys = ['intelirri-project', 'intelirri-projects', 'intelirri-devices', 'intelirri-devicesObj']
	keys.forEach(item => {
		uni.removeStorageSync(item)
	})
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
	if (!source && typeof source !== 'object') {
		throw new Error('error arguments', 'deepClone')
	}
	const targetObj = source.constructor === Array ? [] : {}
	Object.keys(source).forEach(keys => {
		if (source[keys] && typeof source[keys] === 'object') {
			targetObj[keys] = deepClone(source[keys])
		} else {
			targetObj[keys] = source[keys]
		}
	})
	return targetObj
}

/**
 * 判断是否为数字
 * @param {Object} val
 */
export function isNumber(val) {
	if (!isNaN(val)) {
		return true;
	}
	return false
}

/**
 * 获取字符串中的第一个字符
 * @param {Object} val
 */
export function getFirstWord(val) {
	return val.substr(0, 1)
}

export function arrayColumn(arr, column) {
	return arr.map(x => x[column])
}

/**
 * 获取当前日期
 * @returns
 */
export function getCurrentDate() {
	const dateObj = new Date()
	return [dateObj.getFullYear(), (dateObj.getMonth() + 1).toString().padStart(2, 0), dateObj.getDate().toString()
		.padStart(2, 0)
	].join('-')
}

export function getWelcome(hours) {
	let res = '早上好'
	if (hours >= 3 && hours < 6) {
		res = '凌晨了'
	} else if (hours >= 6 && hours < 8) {
		res = '早上好'
	} else if (hours >= 8 && hours < 11) {
		res = '上午好'
	} else if (hours >= 11 && hours < 13) {
		res = '中午好'
	} else if (hours >= 13 && hours < 17) {
		res = '下午好'
	} else if (hours >= 17 && hours < 19) {
		res = '傍晚了'
	} else if (hours >= 19 && hours < 23) {
		res = '晚上好'
	} else {
		res = '夜深了'
	}
	return res
}

/**
 * 获取N天前/后地址
 * @param {*} day 
 */
export function getDateByDays(day = 0) {
	var today = new Date();
	var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
	today.setTime(targetday_milliseconds); //注意，这行是关键代码

	var tYear = today.getFullYear()
	var tMonth = today.getMonth()
	var tDate = today.getDate();

	tMonth = (tMonth + 1).toString().padStart(2, 0);
	tDate = tDate.toString().padStart(2, 0);

	return tYear + "-" + tMonth + "-" + tDate;
}

/**
 * 根据起始日期获取日期数组
 * @param {*} startTime 
 * @param {*} endTime 
 */
export function createDateList(startTime, endTime) {
	endTime = new Date(Date.parse(endTime))
	startTime = new Date(Date.parse(startTime))
	let dateList = []
	let i = 0
	while ((endTime.getTime() - startTime.getTime()) >= 0) {
		let year = startTime.getFullYear()
		let month = startTime.getMonth() + 1
		let day = startTime.getDate()
		dateList[i] = year + '-' +
			(month > 9 ? month : '0' + month) + '-' +
			(day > 9 ? day : '0' + day)
		startTime.setDate(startTime.getDate() + 1)
		i++
	}
	return dateList.reverse()
}

export function trim(value) {
	return value.replace(/(^\s*)|(\s*$)/g, "");
}

export function getHunterAlarmInfo(val, type) {
	const indexes = formatHunterAlarmInfo(val)
	const dict = type === 'info' ? hunterInfoDict : hunterAlarmDict
	const res = []
	indexes.forEach((item) => {
		res.push(dict[item])
	})
	return res.join(',')
}

export function formatHunterAlarmInfo(val) {
	val = val.toString(2).padStart(32, 0)
	const arr = mySplit(val, 8)
	const res = arr.map((item) => {
		return item.split('').reverse().join('')
	}).join('').split('')
	const indexes = []
	res.forEach((item, index) => {
		if (+item === 1) {
			indexes.push(index)
		}
	})
	return indexes
}

export function mySplit(str, len) {
	const arr = []
	let index = 0
	while (index < str.length) {
		arr.push(str.slice(index, index += len))
	}
	return arr
}

export function isJson(str) {
	if (typeof str === 'string') {
		try {
			JSON.parse(str)
			return true
		} catch (e) {
			return false
		}
	}
}

export function unsignToSign(num) { //无符号转有符号  6553 --> -1
	if (num > 0xffff / 2) {
		var a = ~0xffff;
		num = num | a;
	}
	return num;
}

export function signToUnsign(num) { //有符号转无符号  -1 --> 65535
	if (num < 0) {
		num = num & 0xffff;
	}
	return num;
}

/**
 * 计算时间差
 * @param {*} startTime
 * @param {*} endTime
 * @param {*} diffType
 * @returns
 */
export function getDateDiff(startTime, endTime, diffType) {
  // 将xxxx-xx-xx的时间格式，转换为 xxxx/xx/xx的格式
  startTime = startTime.replace(/\-/g, '/')
  endTime = endTime.replace(/\-/g, '/')

  // 将计算间隔类性字符转换为小写
  diffType = diffType.toLowerCase()
  var sTime = new Date(startTime) // 开始时间
  var eTime = new Date(endTime) // 结束时间
  // 作为除数的数字
  var divNum = 1
  switch (diffType) {
    case 'second':
      divNum = 1000
      break
    case 'minute':
      divNum = 1000 * 60
      break
    case 'hour':
      divNum = 1000 * 3600
      break
    case 'day':
      divNum = 1000 * 3600 * 24
      break
    default:
      break
  }
  return parseInt((eTime.getTime() - sTime.getTime()) / parseInt(divNum))
}

export function arraySort(arr, namekey, order = 'desc') {
  if (order === 'desc') {
    return arr.sort((a, b) => {
      return b[namekey] - a[namekey]
    })
  }
  return arr.sort((a, b) => {
    return a[namekey] - b[namekey]
  })
}

export function arraySortForMul(arr, namekey, cNamekey, order = 'desc') {
  if (order === 'desc') {
    return arr.sort((a, b) => {
			return b[namekey][cNamekey] - a[namekey][cNamekey]
    })
  }
  return arr.sort((a, b) => {
    return a[namekey][cNamekey] - b[namekey][cNamekey]
  })
}

export function arraySortForStr(arr, namekey, order = 'desc') {
	let arrMap = arr.map((val) => val[namekey]).sort()
	if(order === 'desc'){
		arrMap = arrMap.reverse()
	}
	const arrObj = convertArr2Obj(arr,'name')
	let res = []
	arrMap.forEach((item) => {
		res.push(arrObj[item])
	})
	return res
}
